/**
 * 智慧小区管理系统 - 物业管理模块API接口
 * @author Wu.Liang
 * @date 2025-06-26
 * @version 3.0 - 根据系统设计调整方案重构，统一接口规范
 */

import api from '@/api/request'
import type {
  ApiResponse,
  PageResponse,
  BaseQueryParams,
  PropertyFee,
  SanitationFee,
  GasFee,
  UtilityFee,
  MeterReading,
  FeeGenerateParams,
  BatchFeeGenerateParams,
  PaymentParams,
  ReminderParams,
  BatchReminderParams,
  FeeStatistics,
  ReminderRecord,
  ReminderStatistics,
  Payment,
  FeeRule,
  Community,
  Building,
  Household,
  FEE_TYPE // 新增
} from '@/views/property/types/property'

// 物业费管理API - 根据接口联调文档重构
export const propertyFeeApi = {
  // 分页查询物业费账单 - 新接口路径
  getPropertyFeeList: (params: BaseQueryParams & { feeType?: FEE_TYPE }) => {
    return api.get<ApiResponse<PageResponse<PropertyFee>>>('/api/property/property-fees', { params })
  },

  // 获取物业费详情 - 新接口路径
  getPropertyFeeDetail: (billId: number) => {
    return api.get<ApiResponse<PropertyFee>>(`/api/property/property-fees/detail/${billId}`)
  },

  // 生成物业费账单 - 新接口路径
  generatePropertyFee: (data: FeeGenerateParams & { 
    billingMonthRange: string[]; 
    dueDate?: string; 
    remark?: string;
  }) => {
    // 严格参数验证
    if (!data.communityId || data.communityId <= 0) {
      throw new Error('小区ID不能为空或无效')
    }
    if (!data.billingMonthRange || data.billingMonthRange.length !== 2) {
      throw new Error('计费月份时间段不能为空')
    }
    if (!data.dueDate) {
      throw new Error('到期日期不能为空')
    }
    
    console.log('物业费生成API请求参数:', {
      communityId: data.communityId,
      billingMonthRange: data.billingMonthRange,
      dueDate: data.dueDate,
      remark: data.remark
    })
    
    // 使用JSON格式发送数据，符合后端@RequestBody的要求
    return api.post<ApiResponse<number>>('/api/property/property-fees/generate', {
      communityId: data.communityId,
      billingMonthRange: data.billingMonthRange,
      dueDate: data.dueDate,
      remark: data.remark
    })
  },

  // 批量生成物业费账单 - 新接口路径
  batchGeneratePropertyFee: (data: BatchFeeGenerateParams & { feeType: number }) => {
    return api.post<ApiResponse<{ [key: string]: number }>>('/api/property/property-fees/batch-generate', data)
  },

  // 查询用户未缴费账单 - 新接口路径
  getUserUnpaidFees: (userId: number) => {
    return api.get<ApiResponse<PropertyFee[]>>(`/api/property/property-fees/user/${userId}/unpaid`)
  },

  // 缴费 - 新接口路径
  payPropertyFee: (billId: number, data: PaymentParams) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/property-fees/pay/${billId}`, null, {
      params: {
        paymentAmount: data.paymentAmount,
        paymentMethod: data.paymentMethod
      }
    })
  },

  // 获取物业费统计信息 - 新接口路径
  getPropertyFeeStatistics: (params: { communityId?: number; year?: number; feeType?: number }) => {
    return api.get<ApiResponse<FeeStatistics>>('/api/property/property-fees/statistics', { params })
  },

  // 发送催缴提醒 - 修正为以查询参数传递提醒方式，符合后端@RequestParam
  sendReminder: (billId: number, remindType: string) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/property-fees/remind/${billId}`, null, {
      params: { remindType }
    })
  },

  // 批量发送催缴提醒 - 新接口路径
  batchSendReminder: (data: BatchReminderParams) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/property-fees/batch-remind', data)
  },

  // 更新费用信息 - 新接口路径
  updatePropertyFee: (billId: number, data: Partial<PropertyFee>) => {
    return api.put<ApiResponse<{ success: boolean }>>(`/api/property/property-fees/update/${billId}`, data)
  },

  // 编辑物业费信息（仅允许编辑指定字段，到期日期不允许修改）
  editPropertyFee: (billId: number, data: { amount: number; paymentStatus: number; feeType?: number; unitPrice?: number }) => {
    return api.put<ApiResponse<{ success: boolean }>>(`/api/property/property-fees/edit/${billId}`, data)
  },

  // 删除费用记录 - 新接口路径
  deletePropertyFee: (billId: number) => {
    return api.delete<ApiResponse<{ success: boolean }>>(`/api/property/property-fees/delete/${billId}`)
  },

  // 导出费用数据 - 新接口路径
  exportPropertyFees: (params: BaseQueryParams & { feeType?: number }) => {
    return api.get('/api/property/property-fees/export', { 
      params,
      responseType: 'blob'
    })
  }
}

// 费用重复检查API
export const feeDuplicateCheckApi = {
  // 检查物业费重复
  checkPropertyFeeDuplicate: (params: {
    communityId: number
    billingPeriod: string
    feeType: number
  }) => {
    return api.post<ApiResponse<FeeDuplicateCheckResult>>('/api/property/fees/check-property-duplicate', null, { params })
  },

  // 检查卫生费重复
  checkSanitationFeeDuplicate: (params: {
    communityId: number
    billingPeriod: string
  }) => {
    return api.post<ApiResponse<FeeDuplicateCheckResult>>('/api/property/fees/check-sanitation-duplicate', null, { params })
  }
}

// 费用重复检查结果类型
export interface FeeDuplicateCheckResult {
  hasDuplicate: boolean
  checkType?: string
  duplicateCount?: number
  duplicateRecords?: DuplicateFeeRecord[]
  errorMessage?: string
  overlappingMonths?: string[]
}

export interface DuplicateFeeRecord {
  feeId: number
  feeNo: string
  householdId: number
  householdAddress?: string
  billingPeriod: string
  amount: string
  paymentStatus: number
  createTime: string
}

// 维修工单管理API - 新增独立接口
export const repairOrderApi = {
  // 分页查询维修工单
  getRepairOrderList: (params: BaseQueryParams & {
    status?: number
    repairType?: number
    urgencyLevel?: number
    startTime?: string
    endTime?: string
  }) => {
    return api.get<ApiResponse<PageResponse<any>>>('/api/property/repair-orders', { params })
  },

  // 获取维修工单详情
  getRepairOrderDetail: (orderId: number) => {
    return api.get<ApiResponse<any>>(`/api/property/repair/${orderId}`)
  },

  // 提交维修工单
  submitRepairOrder: (data: {
    userId: number
    communityId: number
    repairType: number
    title: string
    description: string
    repairAddress: string
    contactPhone: string
    urgencyLevel: number
    residentId?: number
    location?: string
    priority?: number
    remark?: string
  }) => {
    return api.post<ApiResponse<number>>('/api/property/repair/submit', data)
  },

  // 分配维修工单
  assignRepairOrder: (orderId: number, data: {
    assignTo: number
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/repair/${orderId}/assign`, data)
  },

  // 处理维修工单
  processRepairOrder: (orderId: number, data: {
    status: number
    processResult?: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/repair/${orderId}/process`, data)
  },

  // 完成维修工单
  completeRepairOrder: (orderId: number, data: {
    completeResult: string
    satisfaction?: number
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/repair/${orderId}/complete`, data)
  },

  // 取消维修工单
  cancelRepairOrder: (orderId: number, data: {
    cancelReason: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/repair/${orderId}/cancel`, data)
  },

  // 获取维修工单统计
  getRepairOrderStatistics: (params: { communityId?: number; year?: number }) => {
    return api.get<ApiResponse<any>>('/api/property/repair/statistics', { params })
  },

  // 删除维修工单
  deleteRepairOrder: (orderId: number) => {
    return api.delete<ApiResponse<{ success: boolean }>>(`/api/property/repair/${orderId}`)
  }
}

// 水费管理API - 保持原有接口，但路径调整
export const waterFeeApi = {
  // 分页查询水费账单
  getWaterFeeList: (params: BaseQueryParams) => {
    return api.get<ApiResponse<PageResponse<PropertyFee>>>('/api/property/water-fees', { params })
  },

  // 获取水费详情
  getWaterFeeDetail: (billId: number) => {
    return api.get<ApiResponse<PropertyFee>>(`/api/property/water-fees/${billId}`)
  },

  // 提交水表读数
  submitWaterMeterReading: (data: {
    householdId: number
    meterNumber: string
    currentReading: number
    readingDate: string
    readerName: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/water-fees/meter-reading', data)
  },

  // 批量提交水表读数
  batchSubmitWaterMeterReading: (data: {
    readings: Array<{
      householdId: number
      meterNumber: string
      currentReading: number
      readingDate: string
      readerName: string
      remark?: string
    }>
  }) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/water-fees/batch-meter-reading', data)
  },

  // 生成水费账单
  generateWaterFee: (data: FeeGenerateParams) => {
    // 使用URLSearchParams发送表单数据，符合后端@RequestParam的要求
    const params = new URLSearchParams()
    params.append('communityId', data.communityId.toString())
    params.append('billingMonth', data.billingMonth)
    if (data.unitPrice) {
      params.append('unitPrice', data.unitPrice.toString())
    }
    
    return api.post<ApiResponse<{ count: number }>>('/api/property/water-fees/generate', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },

  // 查询用户未缴费水费账单
  getUserUnpaidWaterFees: (userId: number) => {
    return api.get<ApiResponse<PropertyFee[]>>(`/api/property/water-fees/user/${userId}/unpaid`)
  },

  // 水费缴费
  payWaterFee: (billId: number, data: PaymentParams) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/water-fees/${billId}/pay`, data)
  },

  // 获取水费统计信息
  getWaterFeeStatistics: (params: { communityId?: number; year?: number }) => {
    return api.get<ApiResponse<FeeStatistics>>('/api/property/water-fees/statistics', { params })
  }
}

// 电费管理API - 保持原有接口，但路径调整
export const electricityFeeApi = {
  // 分页查询电费账单
  getElectricityFeeList: (params: BaseQueryParams) => {
    return api.get<ApiResponse<PageResponse<PropertyFee>>>('/api/property/electricity-fees', { params })
  },

  // 获取电费详情
  getElectricityFeeDetail: (billId: number) => {
    return api.get<ApiResponse<PropertyFee>>(`/api/property/electricity-fees/${billId}`)
  },

  // 提交电表读数
  submitElectricityMeterReading: (data: {
    householdId: number
    meterNumber: string
    currentReading: number
    readingDate: string
    readerName: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/electricity-fees/meter-reading', data)
  },

  // 批量提交电表读数
  batchSubmitElectricityMeterReading: (data: {
    readings: Array<{
      householdId: number
      meterNumber: string
      currentReading: number
      readingDate: string
      readerName: string
      remark?: string
    }>
  }) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/electricity-fees/batch-meter-reading', data)
  },

  // 生成电费账单
  generateElectricityFee: (data: FeeGenerateParams) => {
    // 使用URLSearchParams发送表单数据，符合后端@RequestParam的要求
    const params = new URLSearchParams()
    params.append('communityId', data.communityId.toString())
    params.append('billingMonth', data.billingMonth)
    if (data.unitPrice) {
      params.append('unitPrice', data.unitPrice.toString())
    }
    
    return api.post<ApiResponse<{ count: number }>>('/api/property/electricity-fees/generate', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },

  // 查询用户未缴费电费账单
  getUserUnpaidElectricityFees: (userId: number) => {
    return api.get<ApiResponse<PropertyFee[]>>(`/api/property/electricity-fees/user/${userId}/unpaid`)
  },

  // 电费缴费
  payElectricityFee: (billId: number, data: PaymentParams) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/electricity-fees/${billId}/pay`, data)
  },

  // 获取电费统计信息
  getElectricityFeeStatistics: (params: { communityId?: number; year?: number }) => {
    return api.get<ApiResponse<FeeStatistics>>('/api/property/electricity-fees/statistics', { params })
  }
}

// 燃气费管理API - 保持原有接口，但路径调整
export const gasFeeApi = {
  // 分页查询燃气费账单
  getGasFeeList: (params: BaseQueryParams & { feeType?: FEE_TYPE }) => {
    return api.get<ApiResponse<PageResponse<GasFee>>>('/api/property/gas-fees', { params })
  },

  // 获取燃气费详情
  getGasFeeDetail: (billId: number) => {
    return api.get<ApiResponse<PropertyFee>>(`/api/property/gas-fees/${billId}`)
  },

  // 提交燃气表读数
  submitGasMeterReading: (data: {
    householdId: number
    meterNumber: string
    currentReading: number
    readingDate: string
    readerName: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/gas-fees/meter-reading', data)
  },

  // 批量提交燃气表读数
  batchSubmitGasMeterReading: (data: {
    readings: Array<{
      householdId: number
      meterNumber: string
      currentReading: number
      readingDate: string
      readerName: string
      remark?: string
    }>
  }) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/gas-fees/batch-meter-reading', data)
  },

  // 生成燃气费账单
  generateGasFee: (data: FeeGenerateParams) => {
    // 使用JSON格式发送数据，符合后端@RequestBody的要求
    return api.post<ApiResponse<{ count: number }>>('/api/property/gas-fees/generate', {
      communityId: data.communityId,
      billingMonth: data.billingMonth,
      unitPrice: data.unitPrice
    })
  },

  // 查询用户未缴费燃气费账单
  getUserUnpaidGasFees: (userId: number) => {
    return api.get<ApiResponse<PropertyFee[]>>(`/api/property/gas-fees/user/${userId}/unpaid`)
  },

  // 燃气费缴费
  payGasFee: (billId: number, data: PaymentParams) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/gas-fees/${billId}/pay`, null, {
      params: {
        paymentAmount: data.paymentAmount,
        paymentMethod: data.paymentMethod
      }
    })
  },

  // 获取燃气费统计信息
  getGasFeeStatistics: (params: { communityId?: number; year?: number }) => {
    return api.get<ApiResponse<FeeStatistics>>('/api/property/gas-fees/statistics', { params })
  }
}

// 卫生费管理API - 保持原有接口，但路径调整
export const sanitationFeeApi = {
  // 分页查询卫生费账单
  getSanitationFeeList: (params: BaseQueryParams & {
    communityId?: number
    paymentStatus?: number
    billingPeriod?: string
    buildingId?: number
    unitId?: number
    householdId?: number
  }) => {
    return api.get<ApiResponse<PageResponse<SanitationFee>>>('/api/property/sanitation-fees', { params })
  },

  // 获取卫生费详情
  getSanitationFeeDetail: (billId: number) => {
    return api.get<ApiResponse<SanitationFee>>(`/api/property/sanitation-fees/${billId}`)
  },

  // 生成卫生费账单
  generateSanitationFee: (data: FeeGenerateParams & { 
    billingMonthRange: string[]; 
    dueDate?: string; 
    remark?: string;
  }) => {
    // 严格参数验证
    if (!data.communityId || data.communityId <= 0) {
      throw new Error('小区ID不能为空或无效')
    }
    if (!data.billingMonthRange || data.billingMonthRange.length !== 2) {
      throw new Error('计费月份时间段不能为空')
    }
    if (!data.dueDate) {
      throw new Error('到期日期不能为空')
    }
    
    console.log('卫生费生成API请求参数:', {
      communityId: data.communityId,
      billingMonthRange: data.billingMonthRange,
      dueDate: data.dueDate,
      remark: data.remark
    })
    
    // 使用JSON格式发送数据，符合后端@RequestBody的要求
    return api.post<ApiResponse<{ count: number }>>('/api/property/sanitation-fees/generate', {
      communityId: data.communityId,
      billingMonthRange: data.billingMonthRange,
      dueDate: data.dueDate,
      remark: data.remark
    })
  },

  // 查询用户未缴费卫生费账单
  getUserUnpaidSanitationFees: (userId: number) => {
    return api.get<ApiResponse<SanitationFee[]>>(`/api/property/sanitation-fees/user/${userId}/unpaid`)
  },

  // 卫生费缴费
  paySanitationFee: (billId: number, data: PaymentParams) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/sanitation-fees/${billId}/pay`, null, {
      params: {
        paymentAmount: data.paymentAmount,
        paymentMethod: data.paymentMethod
      }
    })
  },

  // 编辑卫生费（只允许编辑费用金额、缴费状态，到期日期不允许修改）
  updateSanitationFee: (billId: number, data: {
    amount: number
    // dueDate: string // 注释：到期日期不允许修改
    paymentStatus: number
  }) => {
    return api.put<ApiResponse<{ success: boolean }>>(`/api/property/sanitation-fees/${billId}`, data)
  },

  // 获取卫生费统计信息
  getSanitationFeeStatistics: (params: { communityId?: number; year?: number }) => {
    return api.get<ApiResponse<FeeStatistics>>('/api/property/sanitation-fees/statistics', { params })
  }
}

// 通用API - 保持原有接口
export const commonApi = {
  // 获取小区列表
  getCommunityList: () => {
    return api.get<ApiResponse<Community[]>>('/api/region/communities')
  },

  // 获取楼栋列表
  getBuildingList: (params: { communityId: number }) => {
    return api.get<ApiResponse<Building[]>>('/api/region/buildings', { params })
  },

  // 获取单元列表
  getUnitList: (params: { buildingId: number }) => {
    return api.get<ApiResponse<any[]>>('/api/region/unit/list', { params })
  },

  // 获取房户列表
  getHouseholdList: (params: { communityId?: number; buildingId?: number; unitId?: number }) => {
    return api.get<ApiResponse<Household[]>>('/api/region/households', { params })
  },

  // 获取用户列表
  getUserList: (params: { communityId?: number; keyword?: string }) => {
    return api.get<ApiResponse<any[]>>('/api/user/list', { params })
  }
}

// 水电费管理API - 统一接口
export const utilityFeeApi = {
  // 分页查询水电费账单
  getUtilityFeeList: (params: BaseQueryParams & { feeType?: FEE_TYPE }) => {
    return api.get<ApiResponse<PageResponse<UtilityFee>>>('/api/property/utility-fees', { params })
  },

  // 获取水电费详情
  getUtilityFeeDetail: (billId: number) => {
    return api.get<ApiResponse<PropertyFee>>(`/api/property/utility-fees/${billId}`)
  },

  // 提交表读数
  submitMeterReading: (data: {
    householdId: number
    meterType: 'water' | 'electricity' | 'gas'
    meterNumber: string
    currentReading: number
    readingDate: string
    readerName: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/utility-fees/meter-reading', data)
  },

  // 批量提交表读数
  batchSubmitMeterReading: (data: {
    readings: Array<{
      householdId: number
      meterType: 'water' | 'electricity' | 'gas'
      meterNumber: string
      currentReading: number
      readingDate: string
      readerName: string
      remark?: string
    }>
  }) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/utility-fees/batch-meter-reading', data)
  },

  // 生成水电费账单
  generateUtilityFee: (data: FeeGenerateParams & { feeType: 'water' | 'electricity' | 'gas' }) => {
    return api.post<ApiResponse<{ count: number }>>('/api/property/utility-fees/generate', data)
  },

  // 查询用户未缴费水电费账单
  getUserUnpaidUtilityFees: (userId: number, feeType?: 'water' | 'electricity' | 'gas') => {
    const params = feeType ? { feeType } : {}
    return api.get<ApiResponse<PropertyFee[]>>(`/api/property/utility-fees/user/${userId}/unpaid`, { params })
  },

  // 水电费缴费
  payUtilityFee: (billId: number, data: PaymentParams) => {
    return api.post<ApiResponse<{ success: boolean }>>(`/api/property/utility-fees/${billId}/pay`, null, {
      params: {
        paymentAmount: data.paymentAmount,
        paymentMethod: data.paymentMethod
      }
    })
  },

  // 获取水电费统计信息
  getUtilityFeeStatistics: (params: { communityId?: number; year?: number; feeType?: 'water' | 'electricity' | 'gas' }) => {
    return api.get<ApiResponse<FeeStatistics>>('/api/property/utility-fees/statistics', { params })
  },

  // 异常检测
  checkAnomaly: (params: { communityId?: number; feeType?: 'water' | 'electricity' | 'gas' }) => {
    return api.get<ApiResponse<any[]>>('/api/property/utility-fees/anomaly-check', { params })
  }
}

// 物业公司管理API - 新增物业公司管理接口
export const propertyCompanyApi = {
  // 分页查询物业公司列表
  getPropertyCompanyList: (params: BaseQueryParams & {
    companyName?: string
    companyCode?: string
    contactPerson?: string
    contactPhone?: string
    status?: number
    auditStatus?: number
    qualificationLevel?: string
  }) => {
    return api.get<ApiResponse<PageResponse<any>>>('/api/property/companies/page', { params })
  },

  // 获取物业公司详情
  getPropertyCompanyDetail: (id: number) => {
    return api.get<ApiResponse<any>>(`/api/property/companies/${id}`)
  },

  // 新增物业公司
  createPropertyCompany: (data: {
    companyName: string
    companyCode: string
    businessLicense?: string
    legalRepresentative?: string
    contactPerson: string
    contactPhone: string
    contactEmail?: string
    address?: string
    establishedDate?: string
    registeredCapital?: number
    serviceScope?: string
    qualificationLevel?: string
    paymentQrCode?: string
    paymentAccount?: string
    paymentBank?: string
    paymentLink?: string
    wechatPayMerchantId?: string
    alipayMerchantId?: string
    companyLogo?: string
    introduction?: string
    businessHours?: string
    serviceHotline?: string
  }) => {
    return api.post<ApiResponse<null>>('/api/property/companies', data)
  },

  // 更新物业公司信息
  updatePropertyCompany: (id: number, data: {
    companyName?: string
    businessLicense?: string
    legalRepresentative?: string
    contactPerson?: string
    contactPhone?: string
    contactEmail?: string
    address?: string
    establishedDate?: string
    registeredCapital?: number
    serviceScope?: string
    qualificationLevel?: string
    paymentQrCode?: string
    paymentAccount?: string
    paymentBank?: string
    paymentLink?: string
    wechatPayMerchantId?: string
    alipayMerchantId?: string
    companyLogo?: string
    introduction?: string
    businessHours?: string
    serviceHotline?: string
  }) => {
    return api.put<ApiResponse<null>>(`/api/property/companies/${id}`, data)
  },

  // 删除物业公司
  deletePropertyCompany: (id: number) => {
    return api.delete<ApiResponse<null>>(`/api/property/companies/${id}`)
  },

  // 批量删除物业公司
  batchDeletePropertyCompany: (ids: number[]) => {
    return api.delete<ApiResponse<null>>('/api/property/companies/batch', { data: ids })
  },

  // 审核物业公司
  auditPropertyCompany: (id: number, data: {
    auditStatus: number
    auditRemark?: string
  }) => {
    return api.post<ApiResponse<null>>(`/api/property/companies/${id}/audit`, data)
  },

  // 获取当前用户的物业公司信息
  getCurrentUserPropertyCompany: () => {
    return api.get<ApiResponse<any>>('/api/property/companies/current-user')
  },

  // 更新当前用户的物业公司信息
  updateCurrentUserPropertyCompany: (data: {
    companyName?: string
    contactPerson?: string
    contactPhone?: string
    contactEmail?: string
    address?: string
    businessHours?: string
    serviceHotline?: string
    introduction?: string
  }) => {
    return api.put<ApiResponse<null>>('/api/property/companies/current-user', data)
  },

  // 检查公司编码是否存在
  checkCompanyCodeExists: (companyCode: string, excludeId?: number) => {
    const params = excludeId ? { excludeId } : {}
    return api.get<ApiResponse<boolean>>(`/api/property/companies/check-code/${companyCode}`, { params })
  },

  // 获取物业公司统计信息
  getPropertyCompanyStats: () => {
    return api.get<ApiResponse<any>>('/api/property/companies/stats')
  }
}

 

// 数据权限管理API - 新增数据权限控制接口
export const dataScopeApi = {
  // 获取当前用户数据权限信息
  getDataScopeInfo: () => {
    return api.get<ApiResponse<{
      userId: number
      isSuperAdmin: boolean
      isPropertyCompanyUser: boolean  
      isOwnerUser: boolean
      communityIds: number[]
      propertyCompanyIds: number[]
      restrictions: string
      isSuperAdmin: boolean
      scopeDescription: string
    }>>('/api/property/data-scope/current-user')
  },

  // 检查用户是否有指定小区权限
  checkCommunityPermission: (communityId: number) => {
    return api.get<ApiResponse<{ hasPermission: boolean }>>(`/api/property/data-scope/community/${communityId}/check`)
  },

  // 批量检查用户小区权限
  batchCheckCommunityPermissions: (communityIds: number[]) => {
    return api.post<ApiResponse<{ authorizedCommunityIds: number[] }>>('/api/property/data-scope/community/batch-check', {
      communityIds
    })
  },

  // 获取用户可访问的小区列表
  getUserCommunities: () => {
    return api.get<ApiResponse<number[]>>('/api/property/data-scope/user-communities')
  },

  // 刷新用户权限缓存
  refreshUserPermissionCache: () => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/data-scope/refresh-cache')
  },

  // 清除用户权限缓存
  clearUserPermissionCache: (userId?: number) => {
    return api.delete<ApiResponse<{ success: boolean }>>('/api/property/data-scope/clear-cache', {
      params: { userId }
    })
  }
}

// 物业公司权限管理API - 新增物业公司权限相关接口
export const propertyCompanyPermissionApi = {
  // 检查用户是否为物业公司人员
  checkPropertyCompanyUser: () => {
    return api.get<ApiResponse<{ isPropertyCompanyUser: boolean }>>('/api/property/data-scope/check-property-company-user')
  }
}

// 权限异常处理API - 新增权限异常相关接口
export const permissionExceptionApi = {
  // 获取权限异常详情
  getPermissionExceptionDetail: (errorCode: string) => {
    return api.get<ApiResponse<{
      errorCode: string
      message: string
      solution: string
      contactInfo: string
    }>>(`/api/property/data-scope/exception/${errorCode}`)
  },

  // 提交权限申请
  submitPermissionRequest: (data: {
    requestType: string
    targetCommunityIds?: number[]
    targetPropertyCompanyIds?: number[]
    reason: string
    contactInfo: string
  }) => {
    return api.post<ApiResponse<{ requestId: string }>>('/api/property/data-scope/permission-request', data)
  },

  // 查询权限申请状态
  getPermissionRequestStatus: (requestId: string) => {
    return api.get<ApiResponse<{
      requestId: string
      status: string
      processTime?: string
      result?: string
      remark?: string
    }>>(`/api/property/data-scope/permission-request/${requestId}`)
  }
} 

// 仪表读数管理API - 新增仪表读数相关接口
export const meterReadingApi = {
  // 提交水表读数
  submitWaterMeterReading: (data: {
    householdId: number
    meterNumber: string
    currentReading: number
    readingDate: string
    readerName: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/water-fees/meter-reading', data)
  },

  // 批量提交水表读数
  batchSubmitWaterMeterReading: (data: {
    communityId: number
    readingDate: string
    readerName: string
    readings: Array<{
      householdId: number
      meterNumber: string
      currentReading: number
      remark?: string
    }>
  }) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/water-fees/batch-meter-reading', data)
  },

  // 提交电表读数
  submitElectricityMeterReading: (data: {
    householdId: number
    meterNumber: string
    currentReading: number
    readingDate: string
    readerName: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/electricity-fees/meter-reading', data)
  },

  // 批量提交电表读数
  batchSubmitElectricityMeterReading: (data: {
    communityId: number
    readingDate: string
    readerName: string
    readings: Array<{
      householdId: number
      meterNumber: string
      currentReading: number
      remark?: string
    }>
  }) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/electricity-fees/batch-meter-reading', data)
  },

  // 提交燃气表读数
  submitGasMeterReading: (data: {
    householdId: number
    meterNumber: string
    currentReading: number
    readingDate: string
    readerName: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/gas-fees/meter-reading', data)
  },

  // 批量提交燃气表读数
  batchSubmitGasMeterReading: (data: {
    communityId: number
    readingDate: string
    readerName: string
    readings: Array<{
      householdId: number
      meterNumber: string
      currentReading: number
      remark?: string
    }>
  }) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/gas-fees/batch-meter-reading', data)
  },

  // 通用仪表读数提交
  submitMeterReading: (data: {
    householdId: number
    meterType: string
    meterNumber: string
    currentReading: number
    readingDate: string
    readerName: string
    remark?: string
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/utility-fees/meter-reading', data)
  },

  // 批量通用仪表读数提交
  batchSubmitMeterReading: (data: {
    communityId: number
    meterType: string
    readingDate: string
    readerName: string
    readings: Array<{
      householdId: number
      meterNumber: string
      currentReading: number
      remark?: string
    }>
  }) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/utility-fees/batch-meter-reading', data)
  },

  // 获取仪表读数历史
  getMeterReadingHistory: (params: {
    householdId?: number
    meterType?: string
    startDate?: string
    endDate?: string
  }) => {
    return api.get<ApiResponse<MeterReading[]>>('/api/property/meter-readings/history', { params })
  },

  // 获取仪表信息
  getMeterInfo: (householdId: number, meterType: string) => {
    return api.get<ApiResponse<{
      meterNumber: string
      lastReading: number
      lastReadingDate: string
      meterStatus: string
    }>>(`/api/property/meter-readings/info/${householdId}/${meterType}`)
  }
}

// 区域管理API - 使用统一的regionApi，避免重复定义
// 请使用 @/api/region 中的 regionApi 

// 催缴提醒管理API - 新增催缴提醒相关接口
export const reminderApi = {
  // 新增催缴/沟通记录 - 修正接口地址
  sendReminder: (feeId: number, data: ReminderParams) => {
    return api.post<ApiResponse<{ id: number }>>('/api/property/fees/reminders', data)
  },

  // 批量发送催缴提醒
  batchSendReminder: (data: BatchReminderParams) => {
    return api.post<ApiResponse<{ successCount: number; totalCount: number }>>('/api/property/property-fees/batch-remind', data)
  },

  // 获取催缴记录列表
  getReminderRecords: (params: BaseQueryParams & {
    feeId?: number
    feeType?: number
    status?: number
    startTime?: string
    endTime?: string
  }) => {
    return api.get<ApiResponse<ReminderRecord[]>>('/api/property/fees/reminders', { params })
  },

  // 获取催缴记录详情
  getReminderRecordDetail: (recordId: number) => {
    return api.get<ApiResponse<ReminderRecord>>(`/api/property/fees/reminders/${recordId}`)
  },

  // 更新催缴记录状态
  updateReminderStatus: (recordId: number, data: {
    status: number
    remark?: string
  }) => {
    return api.put<ApiResponse<{ success: boolean }>>(`/api/property/fees/reminders/${recordId}/status`, data)
  },

  // 编辑催缴/沟通记录
  updateReminderRecord: (id: number, data: ReminderParams) => {
    return api.put<ApiResponse<{ id: number }>>(`/api/property/fees/reminders/${id}`, data)
  },

  // 同步催缴记录到主表
  syncToFee: (data: {
    feeId: number
    feeType: number
    nextDueDate?: string
    nextAmount?: number
  }) => {
    return api.post<ApiResponse<{ success: boolean }>>('/api/property/fees/reminders/sync-fee', data)
  },

  // 获取催缴统计信息
  getReminderStatistics: (params: {
    communityId?: number
    year?: number
    reminderType?: string
  }) => {
    return api.get<ApiResponse<ReminderStatistics>>('/api/property/fees/reminders/statistics', { params })
  },

  // 删除催缴记录
  deleteReminderRecord: (recordId: number) => {
    return api.delete<ApiResponse<{ success: boolean }>>(`/api/property/fees/reminders/${recordId}`)
  },

  // 批量删除催缴记录
  batchDeleteReminderRecords: (recordIds: number[]) => {
    return api.delete<ApiResponse<{ success: boolean }>>('/api/property/fees/reminders/batch', { data: recordIds })
  },

  // 获取催缴模板 - 保留原有功能
  getReminderTemplates: () => {
    return api.get<ApiResponse<Array<{
      id: number
      name: string
      content: string
      remindType: string
    }>>>('/api/property/reminder-templates')
  }
} 